<?php
declare (strict_types = 1);

namespace app\service\logic\common\user;

use app\model\communal\UserExpertItemModel;
use app\model\communal\UserExpertModel;
use app\service\logic\BaseService;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;
use think\Model;

final class ExpertItemService extends BaseService
{
    protected string $modelClassName = 'UserExpertItemModel';

    /**
     * 创建
     *
     * @param $params
     * @return Model
     */
    public function create($params)
    {
        Db::connect('communal')->transaction(function () use ($params, &$model) {
            $model = UserExpertItemModel::create($params);
            list($expertItemMin, $expertItemAvg) = $this->getExpertItemData($model['expert_id']);
            UserExpertModel::where('id', $model['expert_id'])->update([
                'minimum_amount' => $expertItemMin,
                'average_amount' => $expertItemAvg,
            ]);
        });
        return $model;
    }

    /**
     * 修改
     *
     * @param $params
     * @return array|mixed|Model
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function item($params)
    {
        $model = $this->getSimpleDetail($params);
        Db::connect('communal')->transaction(function () use ($params, &$model) {
            $model->save($params);
            list($expertItemMin, $expertItemAvg) = $this->getExpertItemData($model['expert_id']);
            UserExpertModel::where('id', $model['expert_id'])->update([
                'minimum_amount' => $expertItemMin,
                'average_amount' => $expertItemAvg,
            ]);
        });
        return $model;
    }

    /**
     * 批量删除
     *
     * @param $params
     * @return bool
     */
    public function batchDelete($params)
    {
        Db::connect('communal')->transaction(function () use ($params, &$result) {
            $ids = explode(',', (string)$params['ids']);
            $expertId = $params['expert_id'];
            $result = UserExpertItemModel::destroy(function ($query) use ($ids, $expertId) {
                $query->whereIn('id', $ids)->where('expert_id', $expertId);
            });

            list($expertItemMin, $expertItemAvg) = $this->getExpertItemData($expertId);
            UserExpertModel::where('id', $expertId)->update([
                'minimum_amount' => $expertItemMin,
                'average_amount' => $expertItemAvg,
            ]);
        });
        return $result;
    }

    /**
     * 重新计算专家项目相关数据搞里头
     *
     * @param $expertId
     * @return array
     */
    public function getExpertItemData($expertId)
    {
        // 项目最低价
        $expertItemMin = UserExpertItemModel::where('expert_id', $expertId)->min('amount');
        // 项目均价
        $expertItemAvg = UserExpertItemModel::where('expert_id', $expertId)->avg('amount');
        return [$expertItemMin, $expertItemAvg];
    }
}
